const ble = require('../../../utils/ble');
const cfg = require('../../../config/ble.config');

Page({
  data: { 
    id: '', 
    ssid: '', 
    pwd: '', 
    percent: 0, 
    status: '准备中', 
    done: false,
    logs: [],
    timeout: null
  },
  
  onLoad(q) {
    this.setData({ 
      id: q.id || '', 
      ssid: decodeURIComponent(q.ssid||''), 
      pwd: decodeURIComponent(q.pwd||'') 
    });
    this.start();
  },

  onUnload() {
    // 清理定时器和监听
    if (this.data.timeout) {
      clearTimeout(this.data.timeout);
    }
    ble.onNotify(null); // 清除监听
  },

  async start() {
    try {
      this.updateStatus('蓝牙连接中...', 10, '蓝牙连接中');
      await ble.connect(this.data.id);
      
      this.updateStatus('发送配网信息...', 25, '蓝牙连接成功');
      const payload = cfg.buildProvisionPayload({ ssid: this.data.ssid, pwd: this.data.pwd });
      
      if (typeof payload === 'string') {
        await ble.writeText(payload);
      } else if (payload && payload.buffer) {
        await wx.writeBLECharacteristicValue({
          deviceId: ble.connectedDeviceId,
          serviceId: ble.serviceId,
          characteristicId: ble.writeChar,
          value: payload.buffer || payload
        });
      } else {
        await ble.writeText(String(payload));
      }
      
      this.updateStatus('等待设备响应...', 40, '设备信息获取成功');
      
      // 设置设备响应监听
      this.setupDeviceListener();
      
      // 设置超时
      this.data.timeout = setTimeout(() => {
        this.handleTimeout();
      }, 30000); // 30秒超时
      
    } catch (e) {
      console.error('配网启动失败:', e);
      this.updateStatus('配网失败，请重试', 0, '配网失败');
      this.setData({ done: true });
    }
  },

  setupDeviceListener() {
    ble.onNotify((res) => {
      try {
        const response = cfg.parseDeviceResponse(res.value);
        if (response) {
          this.handleDeviceResponse(response);
        }
      } catch (e) {
        console.error('处理设备响应失败:', e);
      }
    });
  },

  handleDeviceResponse(response) {
    console.log('设备响应:', response);
    
    const { statusCodes } = cfg;
    const { status, message } = response;
    
    switch (status) {
      case statusCodes.PROVISION_START:
        this.updateStatus('设备开始配网...', 50, '参数信息获取成功');
        break;
        
      case statusCodes.WIFI_CONNECTING:
        this.updateStatus('设备连接WiFi中...', 70, 'WiFi连接中');
        break;
        
      case statusCodes.WIFI_CONNECTED:
        this.updateStatus('WiFi连接成功', 85, 'WiFi连接成功');
        break;
        
      case statusCodes.PROVISION_SUCCESS:
      case statusCodes.DEVICE_READY:
        this.updateStatus('配网成功！', 100, '配网成功');
        this.setData({ done: true });
        if (this.data.timeout) {
          clearTimeout(this.data.timeout);
        }
        break;
        
      case statusCodes.PROVISION_FAILED:
      case statusCodes.WIFI_FAILED:
        this.updateStatus('配网失败：' + (message || '未知错误'), 0, '配网失败');
        this.setData({ done: true });
        if (this.data.timeout) {
          clearTimeout(this.data.timeout);
        }
        break;
        
      default:
        // 其他状态，更新日志
        if (message) {
          this.addLog(message);
        }
    }
  },

  handleTimeout() {
    this.updateStatus('配网超时，请重试', 0, '配网超时');
    this.setData({ done: true });
  },

  updateStatus(status, percent, logMessage) {
    this.setData({ 
      status, 
      percent,
      logs: [...this.data.logs, logMessage]
    });
  },

  addLog(message) {
    this.setData({
      logs: [...this.data.logs, message]
    });
  },

  finish() {
    wx.navigateBack({ delta: 3 });
  },

  retry() {
    this.setData({ 
      percent: 0, 
      status: '准备中', 
      done: false,
      logs: ['准备配网...']
    });
    this.start();
  }
});


